package com.rf.common.utils;

import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.rf.common.response.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @Description 上传七牛云
 * @Author rf
 * @Date 2022/4/11
 */

@Slf4j
public class QiNiuYunUpFileUtils {

    private static final String accessKey = "";
    private static final String secretKey = "";
    private static final String bucket = "";

    public static ResponseVo getUpLoad(MultipartFile uploadFile) {

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huabei());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = UUID.randomUUID() + "-" + uploadFile.getOriginalFilename();
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(uploadFile.getInputStream(), key, upToken, null, null);
            if (response.statusCode == 200) {
                String url = "" + key;
                log.info("文件上传:" + url);
                return ResponseVo.SUCCESS(url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseVo.FAIL;
    }
}
